import ruteDict from "@/dict/route"
import { mapGetters } from "vuex"
import { useColor } from "@/utils/style"
import { baseImageUrl, baseUrl, askUrl } from "@/config"
import { useDict, useDictItem } from "@/utils/dict"
module.exports = {
  data() {
    return {
      // 分享信息
      _shareInfo: {
        title: "", // 默认为小程序名称
        path: "", // 默认为当前页面路径
        imageUrl: "" // 默认为当前页面的截图
      }
    }
  },
  computed: {
    ...mapGetters(["token", "themeColor", "login"]),
    // 主题样式
    useThemeStyle() {
      return (names = ["color"]) => {
        const style = {}
        if (uni.$check.isArray(names)) {
          names.forEach((name) => {
            style[name] = this.themeColor
          })
        } else {
          style[names] = this.themeColor
        }
        return style
      }
    },
    useThemeRGBAStyle() {
      return (names = ["backgroundColor"], alpha = 0.1) => {
        const rgb = uni.$hexToRgb(this.themeColor)
        const style = {}
        if (uni.$check.isArray(names)) {
          names.forEach((name) => {
            style[name] = `rgba(${rgb.r},${rgb.g},${rgb.b}, ${alpha})`
          })
        } else {
          style[names] = `rgba(${rgb.r},${rgb.g},${rgb.b}, ${alpha})`
        }
        return style
      }
    }
  },
  methods: {
    toView(...args) {
      this.$toView(...args)
    },
    useColor(...args) {
      return useColor(...args)
    },
    useRgbColor(color, alpha) {
      const { r, g, b } = uni.$hexToRgb(color)
      return `rgba(${r},${g},${b}, ${alpha})`
    },
    useThemeRgbColor(alpha) {
      const { r, g, b } = uni.$hexToRgb(this.themeColor)
      return `rgba(${r},${g},${b}, ${alpha})`
    },
    // 使用字典
    useDict(...args) {
      return useDict(...args)
    },
    // 使用字典项
    useDictItem(...args) {
      return useDictItem(...args)
    },
    // 图片拼接
    useImage(url) {
      return `${baseImageUrl}${url}`
    },
    // 使用分享
    useShare(data) {
      this._shareInfo = data
    },
    // 使用当前路由
    useCurrentRoute() {
      const routes = getCurrentPages()
      return routes[routes.length - 1]?.route
    },
    // 复制
    useCopy(val) {
      uni.setClipboardData({
        data: val,
        success: () => {
          uni.showToast({ title: "复制成功", duration: 2000, icon: "none" })
        }
      })
    },
    // 使用跳转,一般用于装修的跳转
    useRouteJupm(data) {
      const richJumpType = ["refundAgreement"] // 内部页面富文本装修类型
      const type = data.jumpType
      const value = data.value
      const params = data.params
      const url = data.url
      // 小程序跳转
      if (type == "wxMp") {
        uni.navigateToMiniProgram({ appId: data.wxMpId, path: value, success() {} })
      }
      // tabbar页面跳转
      if (type == "tabbar") {
        const route = ruteDict.find((item) => item.value == value)
        if (route) {
          uni.$toView({ type: route.jumpType, url: route.route, params, login: true })
        } else {
          console.error(`未找到${value}对应的页面，请检查`)
        }
      }
      // 页面跳转
      if (type == "page") {
        // 单独抽离富文本工具类
        if (richJumpType.includes(value)) {
          uni.$setCache("richtext", { content: this.channelInfo["refundAgreement"], title: params.title })
          uni.$toView("pages/utils/richtext/richtext")
        } else {
          const route = ruteDict.find((item) => item.value == value)
          if (route) {
            uni.$toView({ type: route.jumpType, url: route.route, params, login: true })
          } else {
            console.error(`未找到${value}对应的页面，请检查`)
          }
        }
      }
      // 心选微页面跳转
      if (type == "xxMicroPage") {
        if (url) {
          uni.$setCache("webviewSrc", `${url}${url.includes("?") ? "&" : "?"}pageId=${value}`)
          this.toView({ url: "pages/utils/webview/webview" })
        } else {
          console.error(`心选微页面url未配置，请检查`)
        }
      }
      // 小程序跳转
      if (type == "wxMp") {
        uni.navigateToMiniProgram({ appId: data.wxMpAppid, path: data.wxMpPath, success() {} })
      }
      // 链接跳转
      if (type == "url") {
        const handleJump = (url) => {
          // #ifdef WEB
          let regex = /zmaxfilm\.com|zrfilm\.com|heyinmovie\.com/
          if (regex.test(url)) window.location.href = url
          else {
            uni.$setCache("webviewSrc", url)
            this.toView({ url: "pages/utils/webview/webview" })
          }
          // #endif
          // #ifndef WEB
          uni.$setCache("webviewSrc", url)
          this.toView({ url: "pages/utils/webview/webview" })
          // #endif
        }
        // 判断是否需要授权
        if (data.isAuthorizedLogin == 1 && !this.login) {
          const routes = getCurrentPages()
          const route = routes[routes.length - 1].route
          uni.$emit(`${route}-login`)
          return
        } else if (data.isActivityLogin == 1) {
          // 活动联登
          const channelId = data.isSpecifiedChannel == 1 ? data.activityChannelId || "0" : "0"
          console.log("//准备请求 联登到活动页")
          uni.$api.marketingActivity
            .getUnionLoginToken({ jumpUrl: url, channelId: channelId })
            .then((res) => {
              handleJump(res.url)
            })
            .catch(() => {
              console.log("// 联登到活动页请求失败")
            })
        } else {
          // 默认外链跳转
          handleJump(url)
        }
      }
    },
    // 使用广告跳转
    async useAdJump(data = {}) {
      // 埋点
      uni.$api.poster.upAdLog({ adId: data.adId, adType: data.adType, operatorType: "1" })
      const type = data.jump.type
      const value = data.jump.value
      const params = data.jump
      // 电影跳转
      if (type == "filmSource") {
        this.toView({ url: "pages/cinema/film-info/film-info", params: { filmId: value } })
      }
      // 活动跳转
      if (type == "activityPage") {
        this.toView({ url: "pages/main/activity-info/activity-info", params: { activityId: value } })
      }
      // 资讯跳转
      if (type == "informationNew") {
        this.toView({ url: "pages/main/information-info/information-info", params: { informationId: value } })
      }
      // 选座页面跳转
      if (type == "planPage") {
        this.toView({ url: "pages/cinema/cinema-seat/cinema-seat", params: { cinemaId: params.cinemaId, planKey: value } })
      }
      // 影院排期页面跳转
      if (type == "cinemaPlanPage") {
        this.toView({ url: "pages/cinema/cinema-schedule/cinema-schedule", params: { cinemaId: params.value } })
      }
      // 心选微页面跳转
      if (type == "xxScenePage") {
        uni.$setCache("webviewSrc", `${params.wapUrl}${params.wapUrl.includes("?") ? "&" : "?"}pageId=${value}`)
        this.toView({ url: "pages/utils/webview/webview" })
      }
      // 小程序跳转
      if (type == "miniprogram") {
        uni.navigateToMiniProgram({ appId: params.miniprogramId, envVersion: uni.getAccountInfoSync().miniProgram.envVersion, path: value, success() {} })
      }
      // 商品详情跳转
      if (type == "goodsDetail") {
        const route = ruteDict.find((item) => item.value == "mallGoodsDetail")
        if (route) {
          uni.$toView({ type: route.jumpType, url: route.route, params: { mallCommodityId: params.value }, login: true })
        } else {
          console.error(`未找到${value}对应的页面，请检查`)
        }
      }
      // 链接跳转
      if (type == "jumpLink") {
        const handleJump = (url) => {
          // #ifdef WEB
          let regex = /zmaxfilm\.com|zrfilm\.com|heyinmovie\.com/
          if (regex.test(url)) window.location.href = url
          else {
            uni.$setCache("webviewSrc", url)
            this.toView({ url: "pages/utils/webview/webview" })
          }
          // #endif
          // #ifndef WEB
          uni.$setCache("webviewSrc", url)
          this.toView({ url: "pages/utils/webview/webview" })
          // #endif
        }
        // 判断是否需要授权
        if (data.isAuthorizedLogin == 1 && !this.login) {
          const routes = getCurrentPages()
          const route = routes[routes.length - 1].route
          uni.$emit(`${route}-login`)
          return
        } else if (data.isActivityLogin == 1) {
          // 活动联登
          const channelId = data.isSpecifiedChannel == 1 ? data.activityChannelId || "0" : "0"
          console.log("//准备请求 联登到活动页")
          uni.$api.marketingActivity
            .getUnionLoginToken({ jumpUrl: value, channelId: channelId })
            .then((res) => {
              handleJump(res.url)
            })
            .catch(() => {
              console.log("// 联登到活动页请求失败")
            })
        } else {
          handleJump(value)
        }
      }
    },
    // 客服跳转
    async useServiceJump() {
      if (this.login) {
        const userInfo = this.$store.getters.userInfo
        const link = this.$store.getters.baseInfo.onlineServiceUrl || this.$store.getters.baseInfo.aliCustomLine
        const data = { userId: userInfo.memberId, bindingMobile: userInfo.bindingMobile }
        const api = baseUrl.substring(0, baseUrl.length - 4)
        const res = await uni.$request.post(`${api}/event/sms/aliCustomEncryptMsg`, data)
        const url = `${link}&${res.data.encryptMsg}`
        uni.$setCache("webviewSrc", url)
        this.toView({ url: "pages/utils/webview/webview" })
      } else {
        this.$toast("请先登录！")
        const route = this.useCurrentRoute()
        uni.$emit(`${route}-login`)
      }
    },
    // 跳转oss支付
    /**
     * @description 访问OSS地址
     */
    useAskToOSSJump(data) {
      const { payload, action } = data
      const _payload = uni.$encodeParams(payload)
      const url = `${askUrl}?url=${action}&params=${_payload}`
      uni.$setCache("webviewSrc", url)
      this.toView({
        url: "pages/utils/webview/webview"
      })
    }
  }
}
